package c2

import (
	"fmt"
	"strings"
	"time"
)

var counter int
var lastSent time.Time

func SendQiWei(key, title, content string) {
	now := time.Now()
	if now.Sub(lastSent) > time.Minute {
		// 如果距离上次发送的时间超过一分钟，重置计数器和时间戳
		counter = 0
		lastSent = now
	}
	if counter < 15 {
		// 如果在过去的一分钟内发送的消息数量少于15条，发送消息
		res := Post("qiwei", "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=", key)
		res.SetHeader("Content-Type", "application/json")
		if len(content)+len(title) > 4000 {
			// 如果消息内容过长，截断
			content = content[:4000-len(title)-3] + "..."
		}
		body := `
	{
		"msgtype": "markdown",
		"markdown": {
			"content": "%s:\n
			 > %s\n"
		}
	}	
	`
		res.SetBody(fmt.Sprintf(body, title, strings.ReplaceAll(strings.ReplaceAll(content, "\"", "\\\""), "\\\\", "\\")))
		res.Run()
		counter++
		time.Sleep(time.Second)
	} else {
		// 否则，不发送消息
		fmt.Println("Reached the limit of 15 messages per minute")
	}

}
